/**
 * 区域排班 列表页
 *
 * 作者 admin
 * 日期 2024-07-31 14:35:45
 */
layui.use(['laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-baseAreaScheduling'),
        $query = $view.find('#query'),
        $searchForm = $view.find('#baseAreaScheduling-table-form'),
        tableIns;

    form.verify(validate);
    form.render();
    initDate();
    initTable();

    initAreaName();

    function initAreaName() {
        //初始化区域下拉框
        var data = {
            tenantId: $searchForm.find("select[name='tenantId']").find("option:selected").val(),
            status: '1',
        }
        reloadAreaName(data);
    }

    function initDate() {
        //初始化日期控件
        laydate.render({
            elem: '#laydate-range',
            range: ['#start-date', '#end-date'],
            format: 'yyyy-MM-dd',
            btns:['now','confirm']
        })

        $('#end-date').val(commonJS.getNextDateStr(new Date(),7));
        $('#start-date').val(commonJS.getPastDateStr(new Date(),7));
        form.render();

    }

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'baseAreaSchedulingTable',
            url: ctx + 'baseAreaScheduling/list',
            height: getTableHeight(),
            where: getQueryParams(),
            skin: '',
            cols: getCols(),
            toolbar: '#baseAreaScheduling-toolbar',
            defaultToolbar: [],
            done: function (res, curr, count) {
                merge(res);
            }
        });
    }

    table.on('toolbar(baseAreaSchedulingTable)', function (obj) {
        var layEvent = obj.event;
        // console.log('时间'+obj.event);
        if (layEvent === 'addWork') {
            var tenantId = $searchForm.find("select[name='tenantId']").find("option:selected").val();
            febs.modal.open('新增排班', 'baseAreaScheduling/add/'+tenantId, {
                btn: ['提交','取消'],
                area: $(window).width() <= 750 ? '90%' : ['1200px', '650px'],
                yes: function (index, layero) {
                    $('#baseAreaScheduling-edit').find('#submit').trigger('click');
                },
                data:{
                    tenantId: tenantId
                }
            });

        }else if (layEvent === 'scheduleImport') {


        }else if (layEvent === 'scheduleExport') {


        }
    });

    table.on('tool(baseAreaSchedulingTable)', function (obj) {
        let layEvent = obj.event;
        let areaId = obj.data.areaId;
        let startDate = $searchForm.find('input[name="startDate"]').val();
        if(startDate == ''){
            startDate = commonJS.getNextDateStr(new Date(),-7)
        }
        let endDate = $searchForm.find('input[name="endDate"]').val();
        if(endDate == ''){
            endDate = commonJS.getNextDateStr(new Date(),7);
        }
        layEvent = obj.event;
        if (layEvent === 'editWork') {
            febs.modal.open('修改', 'baseAreaScheduling/update/'+areaId+'/'+startDate+'/'+endDate, {
                btn: ['提交','取消'],
                area: $(window).width() <= 750 ? '90%' : ['1200px', '650px'],
                yes: function (index, layero) {
                    $('#baseAreaScheduling-edit').find('#submit').trigger('click');
                },
                data:{
                    tenantId: $searchForm.find('select[name="tenantId"]').val()
                }
            });
        }
    });

    function merge(res) {
        //按字段 合并表格
        var data = res.data;
        if(commonJS.isEmpty(data)){
            return;
        }
        // //console.log("表格数据"+JSON.stringify(data))
        var mergeIndex = 0;//定位需要添加合并属性的行数
        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
        var columsName = ['areaName'];//需要合并的列名称
        var columsIndex = [1];//需要合并的列索引值
        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
            var trArr = $view.find('.layui-table-body').find("tr");//所有行 最大问题出现在此处，获取不到表数据
            for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
                if (data[i][columsName[k]] === data[i - 1][columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
                    mark += 1;
                    tdPreArr.each(function (index,item) {//相同列的第一列增加rowspan属性
                        if(index == 0){
                            $(this).attr("rowspan", mark);
                        }

                    });
                    tdCurArr.each(function (index,item) {//当前行隐藏
                        if(index == 0){
                            $(this).css("display", "none");
                        }
                    });
                } else {
                    mergeIndex = i;
                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                }
            }
            mergeIndex = 0;
            mark = 1;

        }

    }


    function getCols() {
        //拼接动态表头
        var colHead = [];
        var cols = [];
        var colsAll = [];
        febs.getSync(ctx + 'baseAreaScheduling/getDate', getQueryParams(), function (r) {
            colHead = r.data;
            //console.log("获取表头" + colHead);
            let headRow1 = [];
            let headRow1Numbers = getCol('numbers');
            headRow1.push(headRow1Numbers);
            let headRow1AreaName = getCol('areaName');
            headRow1.push(headRow1AreaName);
            r.data.forEach(e=>{
                let date = e;
                let dateObj = {
                    field: 'schedulingDate',
                    title: e,
                    width: 240,
                    align:'center',
                    colspan:3
                }
                headRow1.push(dateObj);
            })

            let headRow2 = [];
            r.data.forEach(e=>{
                let headRow2SchedulingName = getCol("schedulingName"+e);
                headRow2.push(headRow2SchedulingName);
                let headRow2SchedulingTime = getCol("schedulingTime"+e);
                headRow2.push(headRow2SchedulingTime);
                let headRow2SchedulingUser = getCol("schedulingUser"+e);
                headRow2.push(headRow2SchedulingUser);
            })

            colsAll.push(headRow1);
            colsAll.push(headRow2);

        });
        return colsAll;

    }

    function getCol(item) {
        //组装表头明细
        if (item == 'areaName') {
            return {
                field: item,
                title: '区域名称',
                minWidth: 200,
                rowspan:2,
                event:'editWork',
                templet:function (d){
                    return '<p style="color:#01aaed;cursor:pointer">'+d.areaName+'</p>'
                }
            }
        } else if (item.indexOf('schedulingName')>-1) {
            return {
                field: item,
                title: '班次名称',
                minWidth: 200,
                align:'left'
            }
        } else if (item.indexOf('schedulingTime')>-1) {
            return {
                field: item,
                title: '班次时间',
                width: 120,
                align:'center'
            }
        }else if (item.indexOf('schedulingUser')>-1) {
            return {
                field: item,
                title: '负责人',
                width: 100,
                align:'center'
            }
        } else if (item == 'numbers') {
            return {
                type: item,
                title: '序号',
                minWidth: 40,
                fixed: 'left',
                rowspan: 2
            }
        } else {
            return {
                field: item,
                title: item,
                width: 120,
            }
        }
    }

    table.on('sort(baseAreaSchedulingTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    // function reloadPage(curr) {
    //     var _curr = $view.find(".layui-laypage-em").next().html();
    //     if (!!curr) {
    //         _curr = curr;
    //     }
    //     tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    // }

    $query.on('click', function () {
        tableIns.reload({where: getQueryParams(), cols: getCols(), page: {curr: 1}});
        form.render();
    });


    function getQueryParams() {
        // //console.log("areaName=",$searchForm.find('input[name="areaName"]').val());
        // //console.log("startDate=", $searchForm.find('input[name="startDate"]').val());
        // //console.log("endDate=", $searchForm.find('input[name="endDate"]').val());
        // //console.log("tenantId=", $searchForm.find("select[name='tenantId']").find("option:selected").val());
        // //console.log("areaId=", $searchForm.find("select[name='areaId']").find("option:selected").val());
        return {
            areaId: $searchForm.find("select[name='areaId']").find("option:selected").val(),
            startDate: $searchForm.find('input[name="startDate"]').val(),
            endDate: $searchForm.find('input[name="endDate"]').val(),
            tenantId: $searchForm.find("select[name='tenantId']").find("option:selected").val(),
            invalidate_ie_cache: new Date()
        };
    }

    // layui table select 事件
    form.on('select(tenantId)', function (obj) {
        //console.log("选择事件" + obj.value)
        // 获取选中项 value
        var data = {
            tenantId: obj.value
        }
        initAreaName(data);
    });

    function reloadAreaName(data) {
        //根据租户下拉框选项重载区域下拉框
        $("#areaId").empty();
        febs.getSync(ctx + 'baseArea', data, function (r) {
            //console.log("区域列表" + JSON.stringify(r.data))
            var areaLis = r.data;
            var options = '<option value="">请选择</option>';
            $.each(areaLis, function (index, item) {
                options += '<option value="' + item.areaId + '">' + item.areaName + '</option>'

            })
            $("#areaId").append(options);
        });
        form.render();
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }
});